<?php 
namespace app\home\controller;
class Plugin extends Common{

	public function index(){
		$_plug_name = $this -> convertUnderline(\mylib\Input::param('_plug_name', '', [function($str){
					return preg_replace('/[^a-zA-Z]+/','',$str);
				}]));
		$_plug_controller = $this -> convertUnderline(ucfirst(\mylib\Input::param('_plug_controller', '', [function($str){
					return preg_replace('/[^a-zA-Z]+/','',$str);
				}])));
		$_plug_action = $this -> convertUnderline(\mylib\Input::param('_plug_action', '', [function($str){
					return preg_replace('/[^a-zA-Z]+/','',$str);
				}]));

		if (!$cfg = \Plugin::plugins($_plug_name)) {
			return $this -> error('插件不存在！');
		}

		if (!$cfg['status'] && !\mylib\Session::get('admin_login')) {
			return $this -> error('插件未启用！');
		}

		if (!$_plug_name || !$_plug_controller || !$_plug_action) {
			return $this -> error('参数错误！');
		}

		if (!is_dir(PROJECT_PATH . 'plugin/'.$_plug_name)) {
			return $this -> error('插件不存在！');
		}

		$file = PROJECT_PATH . 'plugin/'.$_plug_name.'/controller/' . $_plug_controller . '.php';
		if (!file_exists($file)) {
			return $this -> error('页面不存在！');
		}
		
		require $file;
		if (!is_subclass_of('\\plugin\\' . $_plug_controller, 'Plugin')) {
			return $this -> error('插件必须继承Plugin类！');
		}
		return $this -> exec('\\plugin\\' . $_plug_controller, $_plug_action, null);
	}

	private function exec($class, $action, $param=null){
		if (!class_exists($class)) {
			return $this -> error('插件控制器不存在！');
		}
		$reflector = new \ReflectionClass($class);
		if (!$reflector -> hasMethod($action)) {
			return $this -> error('插件方法不存在！');
		}
		$method = $reflector -> getMethod($action);
		if (!$method -> isPublic()) {
			return $this -> error('插件方法无法执行！');
		}
		if ($method -> isStatic()) {
			return $method -> invoke(null, $param);
		}else{
			return $method -> invoke(new $class(), $param);
		}
	}

	private function convertUnderline($str){
		return preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
			return strtoupper($matches[2]);
		}, $str);
	}
}